package com.yc.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yc.bean.User;
import com.yc.dao.UserDao;
import com.yc.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class UserServiceIml implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Boolean register(String username, String password, String email, String avatar) {
        // 1. 判断用户名是否存在
        Integer count = Math.toIntExact(userDao.selectCount(
                new QueryWrapper<User>().eq("username", username)
        ));
        if (count > 0) {
            return false; // 用户名已存在
        }
        // 判断邮箱是否存在
        count = Math.toIntExact(userDao.selectCount(
                new QueryWrapper<User>().eq("email", email)
        ));
        if (count > 0) {
            return false; // 邮箱已存在
        }

        // 密码加密
        String newpassword = EncryptUtils.encryptToMD5(password);

        // 2. 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(newpassword);
        user.setEmail(email);
        user.setAvatar(avatar);

        // 设置创建时间和更新时间
//        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        user.setCreatedAt(LocalDateTime.parse(currentTime));
//        user.setUpdatedAt(LocalDateTime.parse(currentTime));

        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);

        // 3. 插入用户
        int rows = userDao.insert(user);
        return rows > 0;
    }

    @Override
    public User login(String username, String password) {
        // 1. 根据用户名查找用户
        User user = userDao.selectOne(
                new QueryWrapper<User>().eq("username", username)
        );

        // 2. 用户不存在
        if (user == null) {
            return null;
        }

        // 3. 校验密码（MD5加密）
        String encryptedPassword = EncryptUtils.encryptToMD5(password);
        if (!user.getPassword().equals(encryptedPassword)) {
            return null;
        }

        // 4. 登录成功，返回用户信息（不包含密码）
        user.setPassword(null); // 清空密码，不返回给前端
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        return userDao.selectOne(
                new QueryWrapper<User>().eq("username", username)
        );
    }

    @Override
    public Boolean updateProfile(String username, String email, String avatar, String tags, String interests) {
        // 1. 获取用户信息
        User user = userDao.selectOne(
                new QueryWrapper<User>().eq("username", username)
        );
        if (user == null) {
            return false;
        }

        // 2. 检查邮箱是否被其他用户使用
        if (email != null && !email.trim().isEmpty()) {
            User existingUser = userDao.selectOne(
                    new QueryWrapper<User>().eq("email", email).ne("username", username)
            );
            if (existingUser != null) {
                return false; // 邮箱已被其他用户使用
            }
        }

        // 3. 更新用户信息
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username", username);

        if (email != null && !email.trim().isEmpty()) {
            updateWrapper.set("email", email);
        }
        if (avatar != null) {
            updateWrapper.set("avatar", avatar);
        }
        if (tags != null) {
            updateWrapper.set("tags", tags);
        }
        if (interests != null) {
            updateWrapper.set("interests", interests);
        }

        // 设置更新时间
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        updateWrapper.set("updatedAt", currentTime);

        int rows = userDao.update(null, updateWrapper);
        return rows > 0;
    }

    @Override
    public Boolean changePassword(String username, String currentPassword, String newPassword) {
        // 1. 获取用户信息
        User user = userDao.selectOne(
                new QueryWrapper<User>().eq("username", username)
        );
        if (user == null) {
            return false;
        }

        // 2. 验证当前密码
        String encryptedCurrentPassword = EncryptUtils.encryptToMD5(currentPassword);
        if (!user.getPassword().equals(encryptedCurrentPassword)) {
            return false;
        }

        // 3. 加密新密码
        String encryptedNewPassword = EncryptUtils.encryptToMD5(newPassword);

        // 4. 更新密码
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username", username)
                .set("password", encryptedNewPassword)
                .set("updatedAt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        int rows = userDao.update(null, updateWrapper);
        return rows > 0;
    }

    @Override
    public Boolean deleteAccount(String username) {
        // 1. 检查用户是否存在
        User user = userDao.selectOne(
                new QueryWrapper<User>().eq("username", username)
        );
        if (user == null) {
            return false;
        }

        // 2. 删除用户
        int rows = userDao.delete(
                new QueryWrapper<User>().eq("username", username)
        );
        return rows > 0;
    }
}